package com.lyy.mycart;

import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class CartAdapter extends BaseAdapter {
	private Handler mHandler;
	Context context;
	private int resourceId;// 适配视图资源的id
	List<Cartbean> list;
	LayoutInflater mInflater;

	private static HashMap<Integer, Boolean> isSelected;

	@SuppressLint("UseSparseArrays")
	public CartAdapter(Handler mHandler, Context context, int resourceId,
			List<Cartbean> list) {
		this.mHandler = mHandler;
		this.context = context;
		this.resourceId = resourceId;
		this.list = list;
		mInflater = LayoutInflater.from(context);
		isSelected = new HashMap<Integer, Boolean>();
		initData();
	}

	private void initData() {
		// TODO Auto-generated method stub
		for (int i = 0; i < list.size(); i++) {
			getIsSelected().put(i, false);
		}
	}

	public static HashMap<Integer, Boolean> getIsSelected() {
		// TODO Auto-generated method stub
		return isSelected;
	}

	public static void setIsSelected(HashMap<Integer, Boolean> isSelected) {
		CartAdapter.isSelected = isSelected;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		Cartbean cartbean = list.get(position);
		ViewHolder mHolder = null;
		if (convertView == null) {
			convertView = mInflater.inflate(resourceId, null);
			mHolder = new ViewHolder();
			mHolder.goods_image = (ImageView) convertView
					.findViewById(R.id.goods_image);
			mHolder.goods_name = (TextView) convertView
					.findViewById(R.id.goods_name);
			mHolder.goods_price = (TextView) convertView
					.findViewById(R.id.goods_price);
			mHolder.goods_postage = (TextView) convertView
					.findViewById(R.id.goods_postage);
			mHolder.goods_number = (TextView) convertView
					.findViewById(R.id.goods_number);
			mHolder.goods_check = (CheckBox) convertView
					.findViewById(R.id.goods_check);
			convertView.setTag(mHolder);
		} else {
			mHolder = (ViewHolder) convertView.getTag();
		}
		// mHolder.goods_image.setImageBitmap("http://"+MyApplication.IP+"/8080/StoreDetail/StoreServlet"+cartbean.getImg());
//		MyApplication.bitmapUtils.display(mHolder.goods_image, "http://"
//				+ MyApplication.IP + "/8080/StoreDetail/StoreServlet"
//				+ cartbean.getImg());
//		mHolder.goods_name.setText(cartbean.getName());
//		mHolder.goods_price.setText("商品价格:" + cartbean.getPrice() + "元");
//		mHolder.goods_postage.setText("运费:" + cartbean.getPrice() + "元");
//		mHolder.goods_number.setTag(position);
//		mHolder.goods_number.setText(String.valueOf(cartbean.getAccount()));
		mHolder.goods_number.setOnClickListener(new GoodsNumberClickListener());
		mHolder.goods_check.setChecked(getIsSelected().get(position));
		mHolder.goods_check
				.setOnCheckedChangeListener(new CheckBoxChangedListener());

		return convertView;
	}

	private final class ViewHolder {
		public ImageView goods_image;
		public TextView goods_name, goods_price, goods_postage, goods_number;
		public CheckBox goods_check;
	}

	private final  class GoodsNumberClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String str = ((TextView)v).getText().toString();
			int goodsNum = Integer.valueOf(str);
			showDialog(goodsNum,(TextView)v );
		}

	}

	private int number = 0; // 记录对话框中的数量
	private EditText editnum;

	private void showDialog(int goodsNum, final TextView v) {
		// TODO Auto-generated method stub
		View view = mInflater.inflate(R.layout.number_update, null);
		Button numadd = (Button) view.findViewById(R.id.num_add);
		Button numreduce = (Button) view.findViewById(R.id.num_reduce);
		editnum = (EditText) view.findViewById(R.id.edt_num);
		editnum.setText(String.valueOf(goodsNum));
		numadd.setOnClickListener(new ButtonClickListener());
		numreduce.setOnClickListener(new ButtonClickListener());
		number = goodsNum;
		new AlertDialog.Builder(context).setView(view)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						int postion = (Integer) v.getTag();
						list.get(postion).setAccount(number);
						handler.sendMessage(handler.obtainMessage(1, v));
					}
				}).setNegativeButton("取消", null).create().show();
	}


	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 1) { // 更改商品数量
				((TextView) msg.obj).setText(String.valueOf(number));
				// 更改商品数量后，通知Activity更新需要付费的总金额
				mHandler.sendMessage(mHandler
						.obtainMessage(10, getTotalPrice()));
			} else if (msg.what == 2) {// 更改对话框中的数量
				editnum.setText(String.valueOf(number));
			}
		}
	};

	// Button点击监听器
	private final class ButtonClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (v.getId() == R.id.num_reduce) {
				if (number > 1) {
					number--;
					handler.sendEmptyMessage(2);
				}
			} else if (v.getId() == R.id.num_add) {
				number++;
				handler.sendEmptyMessage(2);
			}
		}
	}

	// CheckBox选择改变监听器
	private final class CheckBoxChangedListener implements
			OnCheckedChangeListener {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			// TODO Auto-generated method stub
			int postion = (Integer) buttonView.getTag();
			getIsSelected().put(postion, isChecked);
			Cartbean cartbean = list.get(postion);
			cartbean.setChoosed(isChecked);
			mHandler.sendMessage(mHandler.obtainMessage(10, getTotalPrice()));
			// 如果所有的物品全部被选中，则全选按钮也默认被选中
			mHandler.sendMessage(mHandler.obtainMessage(11, isAllSelected()));

		}

	}

	// 计算选中商品的金额
	// return 返回需要付费的总金额
	private float getTotalPrice() {
		Cartbean bean = null;
		float totalPrice = 0;
		for (int i = 0; i < list.size(); i++) {
			bean = list.get(i);
			if (bean.isChoosed()) {
				totalPrice += bean.getAccount() * bean.getPrice();
			}
		}
		return totalPrice;
	}

	// 判断是否购物车中所有的商品全部被选中
	// @return true所有条目全部被选中
	// false还有条目没有被选中

	private Object isAllSelected() {
		// TODO Auto-generated method stub
		boolean flag = true;
		for (int i = 0; i < list.size(); i++) {
			if (!getIsSelected().get(i)) {
				flag = false;
				break;
			}
		}

		return flag;
	}

}
